package com.jcw.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcw.common.R;
import com.jcw.domain.Category;
import com.jcw.domain.Dish;
import com.jcw.domain.DishFlavor;
import com.jcw.domain.SetmealDish;
import com.jcw.dto.DishDto;
import com.jcw.service.*;
import com.jcw.mapper.DishMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author JCW
 * @description 针对表【dish(菜品管理)】的数据库操作Service实现
 * @createDate 2023-03-28 11:02:32
 */
@Slf4j
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>
        implements DishService {

    @Resource
    private DishFlavorService dishFlavorService;

    @Resource
    private CategoryService categoryService;

    @Resource
    private SetmealDishService setmealDishService;

    @Resource
    private SetmealService setmealService;

    @Override
    public R<Page> pagination(int page, int pageSize, String name) {
        long beginTime = System.currentTimeMillis();

        Page<Dish> pageInfo = new Page<>(page, pageSize);
        query().like(name != null, "name", name).page(pageInfo);

        Page<DishDto> dishDtoPage = new Page<>();
        BeanUtil.copyProperties(pageInfo, dishDtoPage, "records");

        List<Category> categoryList = categoryService.query().eq("type", 1).list();

        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dish : pageInfo.getRecords()) {
            DishDto dishDto = new DishDto();
            BeanUtil.copyProperties(dish, dishDto);

            Long categoryId = dish.getCategoryId();
            for (Category category : categoryList) {
                if (categoryId.longValue() == category.getId().longValue()) {
                    dishDto.setCategoryName(category.getName());
                    break;
                }
            }
            dishDtoList.add(dishDto);
        }
        dishDtoPage.setRecords(dishDtoList);
        log.info("分页请求花费的时间：" + (System.currentTimeMillis() - beginTime) + " 毫秒");

        return R.success(dishDtoPage);
    }

    @Override
    @Transactional
    public R<String> addDish(DishDto dishDto) {
        Dish dish = new Dish();
        BeanUtil.copyProperties(dishDto, dish, false);
        save(dish);
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
        dishFlavorService.saveBatch(flavors);
        return R.success("菜品添加成功");
    }

    @Override
    public R<DishDto> echoDish(Long id) {
        Dish dish = query().eq("id", id).one();
        List<DishFlavor> flavorList = dishFlavorService.query().eq("dish_id", id).list();

        DishDto dishDto = new DishDto();
        dishDto.setFlavors(flavorList);
        BeanUtil.copyProperties(dish, dishDto);

        return R.success(dishDto);
    }

    @Override
    @Transactional
    public R<String> editDish(DishDto dishDto) {
        Dish dish = new Dish();
        BeanUtil.copyProperties(dishDto, dish);

        List<DishFlavor> flavors = dishDto.getFlavors();

        updateById(dish);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("dish_id", dish.getId());
        dishFlavorService.remove(queryWrapper);

        dishFlavorService.saveBatch(flavors);

        return R.success("修改成功");
    }

    @Override
    public R<String> editStatus(int statusCode, String ids) {
        //将前端传入的字符串拆解成数组
        String[] split = ids.split(",");
        List<Long> idList = new ArrayList();
        for (String s : split) {
            idList.add(Long.valueOf(s));
        }

        //更新菜品状态，停售
        if (statusCode == 0) {
            for (Long id : idList) {
                //查询数据库绑定此菜品的所有套餐
                List<SetmealDish> dishList = setmealDishService.query().eq("dish_id", id).list();
                //判断套餐中是否绑定此菜品
                //菜品没有绑定套餐
                if (dishList.size() == 0){
                    update().eq("id",id).set("status",statusCode).update();
                }else {
                    //菜品绑定了套餐
                    //遍历每一个绑定了此菜品的套餐
                    for (SetmealDish setmealDish : dishList) {
                        //判断套餐是否启售，如果没有启售，则可以修改为停售状态
                        if (setmealService.query().eq("id", setmealDish.getSetmealId()).eq("status", 1).count() < 1) {
                            update().eq("id",id).set("status",statusCode).update();
                            continue;
                        }
                        if(idList.size() == 1){
                            return R.error("菜品与套餐绑定，不可停售");
                        }
                    }
                }
            }
            return R.success("已停售");
        }

        //更新菜品状态，启售
        if (statusCode == 1) {
            for (Long id : idList) {
                update().eq("id", id).set("status", statusCode).update();
            }
        }
        return R.success("已启售");
    }

    @Override
    public R<String> delete(String ids) {
        //将前端传入的字符串拆解成数组
        String[] split = ids.split(",");
        List<Long> idList = new ArrayList();
        for (String s : split) {
            idList.add(Long.valueOf(s));
        }

        for (Long id : idList) {
            if (setmealDishService.query().eq("dish_id", id).count() < 1) {
                removeById(id);
                continue;
            }
            if (idList.size() == 1){
                return R.error("菜品与套餐绑定，不可删除");
            }
        }
        return R.success("已删除");
    }

    @Override
    public R<List> dishList(Long id, Integer status) {
        List<Dish> dishList = query().eq("category_id", id).eq("status",status).list();

        //将菜品和口味包装在一起
        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dish : dishList) {
            DishDto dto = new DishDto();
            BeanUtil.copyProperties(dish,dto);
            List<DishFlavor> flavorList = dishFlavorService.query().eq("dish_id", dish.getId()).list();
            dto.setFlavors(flavorList);
            dishDtoList.add(dto);
        }

        return R.success(dishDtoList);
    }


}




